import Vue from 'vue'
import Vuex from 'vuex'
import Persist from 'vuex-persist'
import router from '../router'
import { login } from '../api'
Vue.use(Vuex)
const persist = new Persist()
const state = {
  token: '',
  userInfo: {}
}
const store = new Vuex.Store({
  state,
  mutations: {
    saveToken: (state, token) => (state.token = token),
    saveUserInfo: (state, userInfo) => (state.userInfo = userInfo)
  },
  actions: {
    async login(ctx, payload) {
      const result = await login(payload)
      if (result) {
        ctx.commit('saveToken', result.data.token)
        ctx.commit('saveUserInfo', result.data.user)
        router.replace('/profile')
      }
    }
  },
  /* 数据持久化设置 */
  plugins: [persist.plugin]
})
export default store
